<template>
  <div ref="chart" style="height: 100%;" />
</template>
<script>
import { Chart } from '@antv/g2';
export default {
  name: 'DashBoardChart',
  props: {
    data: { type: Array, required: true },
    y: { type: String, default: 'y' },
    text: { type: String, required: true }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    data() {
      this.updateData();
    }
  },
  mounted() {
    this.initChart();
    this.drawChart();
  },
  methods: {
    initChart() {
      const ref = this.$refs.chart;
      this.chart = new Chart({
        container: ref,
        width: ref.clientWidth,
        height: ref.clientHeight
      });
    },
    drawChart() {
      // const ref = this.$refs.chart;
      const y = this.y;
      const { PI } = Math;
      const ratio = window.ratio || 1;
      const data1 = [];
      // 内部柱状图长度
      const length = 0.7;
      for (let i = 0; i < 60; i++) {
        data1.push({
          type: i + 'i',
          value: length
        });
      }
      this.chart.data(this.data);
      this.chart.scale(y, {
        min: 0,
        max: 1
      });
      this.chart.coordinate('polar', {
        startAngle: -(12.2 / 9) * PI,
        endAngle: (3.2 / 9) * PI,
        radius: 0.965
      });
      this.chart.axis(y, false);
      this.chart.point().size(0).position(y + '*1');
      // 底色
      this.chart.annotation().arc({
        start: [0, 1],
        end: [1, 1],
        style: {
          stroke: '#4D9B7D',
          lineWidth: 2
        }
      });
      // 指标
      const endValue = this.data[0][y];
      let angle = 0;
      if (this.data[0][y] < 0.5) angle = 270;
      this.chart.annotation().arc({
        start: [0, 1],
        end: [endValue, 1],
        style: {
          stroke: `l(${angle}) 0:#40D965 1:#4D9B7D`,
          lineWidth: 2
        }
      });
      const view = this.chart.createView();
      view.coordinate('polar', {
        radius: 0.85,
        innerRadius: 0.8
      });
      view.data(data1);
      view.tooltip(false);
      view.axis(false);
      view.appendPadding = [6 * ratio, 0, 0, 0];
      view.interval().position('type*value').color('#4D9B7D').size(1.5 * ratio);
      // 内部标注
      view.annotation().text({
        content: `${(endValue * 100).toFixed(0)}%`,
        style: {
          fill: '#52F3A3',
          fontSize: 16 * ratio,
          textAlign: 'center'
        },
        position: ['50%', '40%']
      });
      view.annotation().text({
        content: this.text,
        style: {
          fill: '#CDDEEF',
          fontSize: 12 * ratio,
          textAlign: 'center'
        },
        position: ['50%', '65%']
      });
      this.chart.render();
    },
    updateData() {
      this.chart.clear();
      this.drawChart();
    }
  }
};
</script>
